package com.xingfly.service;

import com.xingfly.model.User;
import com.xingfly.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

/**
 * Created by SuperS on 17/05/2017.
 *
 * @author SuperS
 */
@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ImageService imageService;
    @Autowired
    private PostService postService;
    @Autowired
    private FeedService feedService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private EventService eventService;
    @Autowired
    private NotificationService notificationService;
    @Autowired
    private FriendService friendService;
    @Autowired
    private RoleService roleService;

    //分页获取所有用户
    public Page<User> getUsers(Pageable pageable) {
        return userRepository.findAll(pageable);
    }
    //创建用户
    public User create(User user) {
        //加密密码
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        return userRepository.save(user);
    }
    //更用户名和密码查找用户
    public User findByUserNameAndPassWord(String username, String password) {
        return userRepository.findByUsernameAndPassword(username, password);
    }
    //根据用户id
    public User findById(Long id) {
        return userRepository.findOne(id);
    }
    //删除用户的所有数据
    @Transactional
    public void delete(Long uid) {
        roleService.deleteAllByUserId(uid);
        postService.deleteAllByUserId(uid);
        imageService.deleteImagesByUserId(uid);
        notificationService.deleteAllByUserId(uid);
        friendService.deleteAllByUserId(uid);
        feedService.deleteAllByAuthorId(uid);
        eventService.deleteAllByUserId(uid);
        commentService.deleteAllByUserId(uid);
        userRepository.delete(uid);
    }
    //根据用户名查找用户
    public User findByUserName(String username) {
        return userRepository.findByUsername(username);
    }
}
